#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define BUFSIZE (1 * 1024 * 1024)

int main(int argc, char * argv[])
{
	int sfd, dfd;
	char buf[BUFSIZE];
	int len;
	int ret;
	int pos;
	//参数检验
	if(argc < 3)
	{
		fprintf(stderr, "arg err\n");
		exit(1);
	}
	//打开文件
	sfd = open(argv[1], O_RDONLY);
	if(sfd < 0)
	{
		fprintf(stderr, "open s err\n");
		exit(1);
	}
	dfd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0600);
	if(dfd < 0)
	{
		fprintf(stderr, "open d err\n");
		close(sfd);
		exit(1);
	}
	//循环
	while(1)
	{
		//成功返回读到的字节数,0为读到文件尾
		len = read(sfd, buf, BUFSIZE);
		if(len < 0)
		{
			perror("read");
			break;
		}
		if(len == 0)
		{
			break;
		}

		//坚持写完len字节
		pos = 0;
		while(len > 0)
		{
			ret = write(dfd, buf + pos, len);
			if(ret < 0)
			{
				perror("write");
				exit(1);
			}
			pos += ret;
			len -= ret;
		}
	}
	//关闭文件
	close(dfd);
	close(sfd);

	exit(1);
}
